<?php

use Illuminate\Database\Capsule\Manager as DB;

class FaqController extends CommonController
{
    protected $authExcept = ['index', 'detail'];

    public function indexAction()
    {
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;
        $offset = ($page - 1) * $per_page;

        $total = DB::table('sys_faq')->count();
        $data = DB::table('sys_faq')
            ->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($per_page)
            ->get();

        $result = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];

        json(['code' => 1, 'msg' => '常见问题', 'data' => $result]);
    }

    public function faqHuifuAction()
    {
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;
        $offset = ($page - 1) * $per_page;
        $user = \app\service\auth::getUser();
        $total = DB::table('feedback')->where(['user_id'=>$user->id])->count();
        $data = DB::table('feedback')->where(['user_id'=>$user->id])
            ->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($per_page)
            ->get();

        $result = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];

        json(['code' => 1, 'msg' => '常见问题', 'data' => $result]);
    }

    public function detailAction()
    {
        $id = $this->get('id', 0);
        $data = DB::table('faq')->find($id);
        json(['code' => 1, 'msg' => '问题详情', 'data' => $data]);
    }

    public function addAction()
    {
        $params = $this->getPost();
        $user = \app\service\auth::getUser();
        if(empty($params['content'])){
            json(['code' => 0, 'msg' => '请输入内容']);
        }
        $inser_arr['user_id'] = $user->id;
        $inser_arr['content'] = $params['content'];
        if(!empty($params['images'])){
            $inser_arr['image']  = $params['images'][0];
        }
        if(!empty($params['phone'])){
            $inser_arr['phone']  = $params['phone'];
        }
        $inser_arr['created_at'] = date("Y-m-d H:i:s");
        $inser_arr['username']   = $user->nickname;
        DB::table('feedback')->insert($inser_arr);
        json(['code' => 1]);
    }
}
